package demo.controller;


import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import demo.entity.User;


@Controller
@RequestMapping("login")
public class LoginController {

	@RequestMapping("login_show")
	@RequiresGuest
	public ModelAndView showLoginPage() {
		ModelAndView modelAndView = new ModelAndView("login");
		return modelAndView;
	}

	@RequestMapping("error_show")
	public ModelAndView showErrorPage() {
		ModelAndView modelAndView = new ModelAndView("error");
		return modelAndView;
	}
	
	/**
	 * 登录方法
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public String login(User user, HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try{
			subject.login(token);
			request.getSession().setAttribute("user", user);
			return "redirect:/user/success.do";
		}catch(Exception e){
			e.printStackTrace();
			request.getSession().setAttribute("user", user);
			request.setAttribute("error", "login.error");
			return "login";
		}
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		SecurityUtils.getSubject().logout();
		return "redirect:/login/login_show.do";
	}
	
	@RequestMapping("unauthorized_show")
	public ModelAndView showUnauthorizedPage() {
		ModelAndView modelAndView = new ModelAndView("unauthorized");
		return modelAndView;
	}
	

}
